package cn.tjad.tjad2.module.document.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.bean.CommonListBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.bean.PermissionBean;
import cn.tjad.tjad2.data.bean.Project;
import cn.tjad.tjad2.listener.OnItemLongClickListener;
import cn.tjad.tjad2.module.document.adapter.DocPermissionAdapter;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

public class PermissionFragment extends BaseFragment implements IDataCallBack, OnItemLongClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    private DocPermissionAdapter adapter;
    private int projectId;
    private FileBean fileBean;

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.common_recylerview, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle == null) {
            Tools.showToast("没有有效的参数");
            getActivity().finish();
        } else {
            fileBean = (FileBean) bundle.getSerializable(Keys.FILE);
            if (fileBean == null) {
                Tools.showToast("没有有效的参数");
                getActivity().finish();
            }
        }
        swipeRefreshLayout.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        adapter = new DocPermissionAdapter(null);
        adapter.setOnItemLongClickListener(this);
        recyclerView.setAdapter(adapter);
        projectId = TjadApplication.getInstance().getSession().getProjectId();
//        requestPermissionList();
    }

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.showRight(true);
        titleView.setRightText("新增");
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                Bundle bundle = new Bundle();
                bundle.putInt(Keys.PERMISSION_TYPE, 0);
                bundle.putSerializable(Keys.PERMISSION, null);
                bundle.putInt(Keys.FILE, fileBean.id);
                RouteUtils.toPage(getContext(), PageId.PERMISSION_UPDATE, bundle);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        RemoteDataService.getPermissionList(projectId, fileBean.id, this);
    }

    private void requestPermissionList() {
        RemoteDataService.getPermissionList(projectId, fileBean.id, this);
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        switch (httpId) {
            case HttpId.PERMISSION_LIST:
                if (TextUtils.isEmpty(errorMsg)) {
                    Tools.showToast("获取当前文件夹权限列表失败");
                } else {
                    Tools.showToast(errorMsg);
                }
                swipeRefreshLayout.setRefreshing(false);
                break;
            case HttpId.DELETE_PERMISSION:
                if (TextUtils.isEmpty(errorMsg)) {
                    Tools.showToast("删除权限失败");
                } else {
                    Tools.showToast(errorMsg);
                }
                break;
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        switch (httpId) {
            case HttpId.PERMISSION_LIST:
                CommonListBean<PermissionBean> bean = (CommonListBean<PermissionBean>) responseBean;
                if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                    if (fileBean != null) {
                        Project project = TjadApplication.getInstance().getSession().getProject();
                        PermissionBean permission = new PermissionBean();
                        permission.user = project.admin;
                        permission.user.title = "项目架构管理员";
                        if (fileBean.permission != null) {
                            permission.view = fileBean.permission.view;
                            permission.create = fileBean.permission.create;
                            permission.download = fileBean.permission.download;
                            permission.move = fileBean.permission.move;
                            permission.rename = fileBean.permission.rename;
                            permission.setPermission = fileBean.permission.setPermission;
                        }
                        bean.result.add(0, permission);
                    }
                    adapter.updateData(bean.result);
                    adapter.notifyDataSetChanged();
                } else {
                    Tools.showToast(bean.respMsg);
                }
                swipeRefreshLayout.setRefreshing(false);
                break;
            case HttpId.DELETE_PERMISSION:
                CommonBean<BaseBean> bean1 = (CommonBean<BaseBean>) responseBean;
                if (bean1.resCode == HttpConstants.CODE_SUCCESS) {
                    Tools.showToast("权限删除成功!");
                    requestPermissionList();
                } else {
                    Tools.showToast(bean1.respMsg);
                }
                break;
        }
    }

    @Override
    public boolean onItemLongClick(View parentView, View itemView, int position) {
        if (position == 0) {
            //第一条不让修改
            return true;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        final PermissionBean bean = adapter.getItemData(position);
        String title = "请选择操作";
        if (bean.company != null) {
            title = bean.company.name;
        } else if (bean.department != null) {
            title = bean.department.name;
        } else if (bean.user != null) {
            title = bean.user.name;
        }
        String[] choices = new String[] {"新增", "修改", "删除"};
        builder.setTitle(title)
                .setSingleChoiceItems(choices, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                            case 0:
                                Bundle bundle = new Bundle();
                                bundle.putInt(Keys.PERMISSION_TYPE, 0);
                                bundle.putSerializable(Keys.PERMISSION, null);
                                bundle.putInt(Keys.FILE, fileBean.id);
                                RouteUtils.toPage(getContext(), PageId.PERMISSION_UPDATE, bundle);
                                break;
                            case 1:
                                Bundle bundle1 = new Bundle();
                                bundle1.putInt(Keys.PERMISSION_TYPE, 1);
                                bundle1.putSerializable(Keys.PERMISSION, bean);
                                bundle1.putInt(Keys.FILE, fileBean.id);
                                RouteUtils.toPage(getContext(), PageId.PERMISSION_UPDATE, bundle1);
                                break;
                            case 2:
                                confirmBeforDelete(bean);
                                break;
                        }
                        dialogInterface.dismiss();
                    }
                })
                .show();
        return true;
    }

    private void confirmBeforDelete(final PermissionBean bean) {
        String title = "";
        if (bean.company != null) {
            title = bean.company.name;
        } else if (bean.department != null) {
            title = bean.department.name;
        } else if (bean.user != null) {
            title = bean.user.name;
        }
        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
        builder.setTitle(title)
                .setMessage("是否要删除该权限?")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        RemoteDataService.deletePermission(projectId, fileBean.id, bean.id, PermissionFragment.this);
                        return true;
                    }
                })
                .show(getChildFragmentManager());
    }

    @Override
    public void onRefresh() {
        requestPermissionList();
    }
}
